﻿using MediatR;
using SmartCity.ProcessEngine.Api.Read.Application.Command.FormCategory;
using SmartCity.ProcessEngine.Api.Read.Dtos;
using SmartCity.ProcessEngine.Domain.Entities;
using SmartCity.ProcessEngine.ErrorCode;
using SmartCity.ProcessEngine.Infrastructure.Extention;
using SmartCity.ProcessEngine.Infrastructure.Interface;

namespace SmartCity.ProcessEngine.Api.Read.Application.CommandHandler.FormCategory
{
    public class SearchFormCategoryHandler : IRequestHandler<SearchFormCategoryCommand, ApiResult<List<Dtos.FormCategoryDto>>>
    {
        private readonly IBaseRepository<IndustryModel> industryRepo;
        private readonly IBaseRepository<FormCategoryModel> formCategoryRepo;

        public SearchFormCategoryHandler(IBaseRepository<IndustryModel> industryRepo, IBaseRepository<FormCategoryModel> formCategoryRepo)
        {
            this.industryRepo = industryRepo;
            this.formCategoryRepo = formCategoryRepo;
        }

        public async Task<ApiResult<List<FormCategoryDto>>> Handle(SearchFormCategoryCommand request, CancellationToken cancellationToken)
        {
            var formCategorys = formCategoryRepo.GetAll().Where(x => !x.IsDeleted);
            var indus = industryRepo.GetAll().Where(x => !x.IsDeleted);
            //条件判断
            if (request.IndustryId != null) {//所属行业
                indus = indus.Where(x=>x.Id ==request.IndustryId);
            }
            if (request.FormCategoryName.IsNotNull()) {//类别名称
                formCategorys = formCategorys.Where(x=>x.FormCategoryName.Contains(request.FormCategoryName));
            }

            var linq = from f in formCategorys
                       join i in indus on f.IndustryId equals i.Id
                       select new Dtos.FormCategoryDto
                       {
                           Id = f.Id,
                           IndustryId = i.Id,
                           FormCategoryCode = f.FormCategoryCode,
                           FormCategoryName = f.FormCategoryName,
                           IndustryName = i.IndustryName,
                       };

            return  new ApiResult<List<FormCategoryDto>>().Success("查询表单类别列表成功",linq.ToList());
        }
    }
}
